package com.jjh.jhwebserver.handler;

import com.jjh.jhwebserver.context.HttpServletResponse;
import com.jjh.jhwebserver.context.JhResponse;
import com.jjh.jhwebserver.util.FileUtils;
import com.jjh.jhwebserver.util.TimeUtil;

import java.io.*;
import java.net.Socket;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;

import static java.lang.System.in;
import static java.lang.System.out;

/**
 * 对响应进行处理
 * @author JJH
 */
public class JhResponseHandler {

    private JhResponse response;

    private OutputStream outputStream;


    public JhResponseHandler(JhResponse response,OutputStream outputStream) throws FileNotFoundException {
        this.response = response;
        this.outputStream = outputStream;
        handleResponse(response,outputStream);
    }

    /**
     * 处理响应，可以是所有类型的响应
     * @param response
     * @param outputStream
     */
    private void handleResponse(JhResponse response,OutputStream outputStream) throws FileNotFoundException {
        if(response.getClass()== HttpServletResponse.class){
            //转化为http的响应对象
            HttpServletResponse response1 = (HttpServletResponse) response;

            handleHttpResponse(response1,outputStream);

        }
    }

    /**
     * 处理http的响应
     */
    private void handleHttpResponse(HttpServletResponse response,OutputStream outputStream) throws FileNotFoundException {

        //添加一些统一的响应头
        //设置响应的时间
        response.setHeader("Date:"+ TimeUtil.now());
        response.setHeader("Server:JhWebServer");


        //获取它的状态码，来判断
        int status = response.getStatus();
        if(status==200){
            StringBuffer sb = new StringBuffer();
            //200 OK,返回一个正确结果
            String row = "HTTP/1.1 200 OK\r\n";
            sb.append(row);
            HashMap<String, String> headers = response.getHeaders();
            headers.forEach((head,value)->{
                sb.append(head).append(":").append(value).append("\r\n");
            });
            //判断一下是那种格式
                if(headers.get("Content-Type")!=null) {
                    byte[] bytes;

                    String type = headers.get("Content-Type");

                    if(type.contains("jpg")||type.contains("jpeg")||type.contains("png")
                    ||type.contains("webp")){
                        sb.append("\r\n");

                        File resFile = response.getResFile();
                        byte[] fileByte = FileUtils.getFileByte(resFile);
                        for (byte b : fileByte) {
                            sb.append(b);
                        }
                        try {
                            outputStream.write(sb.toString().getBytes());
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }else {
                        sb.append("\r\n");
                        sb.append(response.getResponseBody());
                         bytes = sb.toString().getBytes();
                        try {
                            outputStream.write(bytes);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }else {
                    //主要是options请求
                    if(!("").equals(response.getHeader("Access-Control-Allow-Headers"))){
                        try {
                            outputStream.write(sb.toString().getBytes());
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }else{
                        //默认没设置响应的格式，那么我们设置为html文本
                        sb.append("Content-Type:text/html; charset=utf-8\r\n");
                        sb.append("Content-Length:").append(response.getResponseBody().length()).append("\r\n");
                        sb.append("\r\n\r\n");
                        sb.append(response.getResponseBody());
                        try {
                            outputStream.write(sb.toString().getBytes());
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }else if (status==404) {
                StringBuffer sb = new StringBuffer();
                String row = "HTTP/1.1 404\r\n";
                sb.append(row);
                HashMap<String, String> headers = response.getHeaders();
                response.setHeader("Content-Type:text/html; charset=utf-8");
                headers.forEach((head,value)->{
                    sb.append(head+":"+value+"\r\n");
                });
                sb.append("\r\n");
                sb.append("<!DOCTYPE html>\n" +
                        "<html lang=\"en\">\n" +
                        "<head>\n" +
                        "    <meta charset=\"UTF-8\">\n" +
                        "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
                        "    <title>NotFound</title>\n" +
                        "</head>\n" +
                        "<body>\n" +
                        "    <h1>404 Not Found</h1>\n" +
                        "</body>\n" +
                        "</html>");
            try {
                outputStream.write(sb.toString().getBytes());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }


    }









}
